import {ref} from "vue";
import {post} from "./api";
import {onPullDownRefresh, onReachBottom, onShow} from "@dcloudio/uni-app";

export function usePageData(functionMethod, searchObject) {

    let pageData = ref({
        size:10,
        total:0,
        totalPage:0,
        data:[]
    })

    let loading = ref(false)

    //总页数
    const totalPage = ref(0)
    //总条数
    const total = ref(0)


    //加载的状态
    const status = ref("more")
    const searchList = async () => {
        loading.value = true;
        let res =await loadData()
        if (res.code === 200) {
            pageData.value = res;
            totalPage.value=res.totalPage;
        }
        loading.value = false;
    }

    const loadData = async () => {
        let data = {};
        data.model = functionMethod;
        data.filters=searchObject.value;
        data.page=searchObject.value.page;
        data.size=searchObject.value.size;

        return  post(`/data/search`, data);
    }




    const search = async () => {
        searchObject.value.page = 1;
        await searchList();
    }


    const loadMore = async () => {

        searchObject.value.page = searchObject.value.page + 1;
        if(searchObject.value.page>totalPage.value){
            status.value = "noMore";
            return;
        }
        let res = await loadData();
        if (res.code !== 200) {
            return;
        }
        checkMore(res)
        if (res.data) {
            pageData.value.data = pageData.value.data.concat(res.data);
        }

    }

    const checkMore = (res) => {
        totalPage.value = res.totalPage;
        total.value = res.total;
        if (searchObject.value.no < res.totalPage) {
            status.value = "loading";
        } else {
            status.value = "noMore";
        }

    }
    onShow(async () => {
        await search();
    })

    onPullDownRefresh(async () => {
        await search();
        uni.stopPullDownRefresh();
    })
    onReachBottom(async () => {
        await loadMore();
    });

    return {pageData,status, searchList, search,checkMore,loading}

}
